import axios from 'axios'
import { ElMessage } from 'element-plus'
import userStore from '@/store/modules/user'

const request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000, //5秒
})

// 请求前拦截器
request.interceptors.request.use(
  (config) => {
    let useUserStore = userStore()
    const token = useUserStore.token
    if (token) {
      //请求头信息赋值
      config.headers.token = token
      //todo: 登录成功后的token存到缓存里, 这里从缓存里取token值
    }
    return config //这个值一定要返回
  },
  (error) => {
    return Promise.reject(error)
  },
)

request.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      return Promise.resolve(response.data)
    } else {
      return Promise.reject(response.data)
    }
  },
  (error) => {
    //处理网络错误
    let msg = ''
    let status = error.response?.status || error.code
    switch (status) {
      case 401:
        msg = 'token过期'
        break
      case 403:
        msg = '无权访问'
        break
      case 404:
        msg = '请求地址错误'
        break
      case 500:
        msg = '服务器出现问题'
        break
      case 'ECONNABORTED':
        msg = '请求超时'
        break
      default:
        msg = '无网络'
        break
    }
    ElMessage({
      type: 'error',
      message: msg,
    })
    return { code: status, message: msg }
  },
)

export default request
